package com.recruit.business.controller;

import cn.hutool.core.date.DateUtil;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import com.recruit.common.model.EducationDO;
import com.recruit.common.model.ExperienceDO;
import com.recruit.common.model.ProjectDO;
import com.recruit.common.service.ResumeService;
import com.recruit.common.service.UserService;
import com.recruit.common.vo.ResumeVO;
import io.github.talelin.autoconfigure.exception.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Positive;
import java.io.File;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class PDFController {
    @Autowired
    private ResumeService resumeService;
    @Autowired
    private UserService userService;

//    @Value("${lin.file.serve-path:assets/**}")
//    private String servePath;

//    @Autowired
//    private FileProperties fileProperties;


    public Map<String,Map> fillData(ResumeVO resume){
        Map<String,Map> map = new HashMap<>();
        // 模板中需要填充的数据
        Map data = new HashMap<String, String>();
        data.put("name",resume.getName());
        data.put("spe",resume.getJobIntention());
        data.put("sex","0".equals(resume.getSex())?"男":"女");
        data.put("english",resume.getEnglish());
        data.put("addr",resume.getHome());
        data.put("age",resume.getAge());
        data.put("tel",resume.getTel());
        data.put("email",resume.getEmail());


        //学历（0 高中，1 大学专科，2 大学本科，3 硕士研究生， 4 博士研究生）
        List<EducationDO> eduList = resume.getEducations();
        String eduString = "";
        if(eduList != null & eduList.size() > 0){
            for(EducationDO edu:eduList) {
                eduString+=edu.getName();
                eduString+="                                 "+edu.getMajor();
                //学历（0 高中，1 大学专科，2 大学本科，3 硕士研究生， 4 博士研究生）
                if(edu.getDiploma() == 0) {
                    eduString+="                                 "+"高中";
                } else if(edu.getDiploma() == 1) {
                    eduString+="                                 "+"大学专科";
                } else if(edu.getDiploma() == 2) {
                    eduString+="                                 "+"大学本科";
                } else if(edu.getDiploma() == 3) {
                    eduString+="                                 "+"硕士研究生";
                } else if(edu.getDiploma() == 4) {
                    eduString+="                                 "+"博士研究生";
                }
                eduString+="                                                                     "+ DateUtil.format(edu.getStartTime(),"yyyy.MM")+"-"+DateUtil.format(edu.getEndTime(),"yyyy.MM");
                eduString+="\n";
                eduString+=""+edu.getDescriptions();
                eduString+="\n";
            }
        }
        data.put("jybj",eduString);//教育经历


        data.put("zyjn",resume.getAbility());//专业技能

        List<ExperienceDO> expList = resume.getExperiences();
        String expString = "";
        if(expList != null & expList.size() > 0){
            for(ExperienceDO exp:expList) {
                expString+=exp.getName();
                expString+="                                                      "+exp.getPosition();
                expString+="                                                                     "+ DateUtil.format(exp.getStartTime(),"yyyy.MM")+"-"+DateUtil.format(exp.getEndTime(),"yyyy.MM");
                expString+="\n";
                expString+=""+exp.getPerformance();
                expString+="\n";
            }
        }
        data.put("sxjy",expString);//实习经历


        List<ProjectDO> proList = resume.getProjects();
        String proString = "";
        if(proList != null & proList.size() > 0){
            for(ProjectDO pro:proList) {
                proString+=pro.getName();
                proString+="                                                                     "+ DateUtil.format(pro.getStartTime(),"yyyy.MM")+"-"+DateUtil.format(pro.getEndTime(),"yyyy.MM");
                proString+="\n";
                proString+="项目背景：\n";
                proString+="    "+pro.getBackground()+"\n";
                proString+="项目描述：\n";
                proString+=""+pro.getPerformance();
                expString+="\n";
            }
        }
        data.put("xmjl",proString); //项目经历

        data.put("grpj",resume.getPersonalSummary()); // 个人总结


        //头像 图片 url
        Map image = new HashMap<String, String>();
        //image.put("img_af_image","C:\\Users\\Public\\Pictures\\10300933262330000.jpg");
//        http://localhost:5000/assets/2023/09/15/14081e4032e544228ed81b00f1aff577.jpg
//        System.out.println("getStoreDir: " + FileUtil.getFileAbsolutePath(fileProperties.getStoreDir(),resume.getAvatar()));
//        image.put("img_af_image",FileUtil.getFileAbsolutePath(fileProperties.getStoreDir(),resume.getAvatar()));


        //image.put("img_af_image","C:\\Users\\Public\\Pictures\\10300933262330000.jpg");

        map.put("data",data);
        map.put("image",image);
        return map;
    }

    @GetMapping("/pdf/{userId}")
    public void downLoadPdf(HttpServletResponse response,@PathVariable(value = "userId") @Positive(message = "{id.positive}") Integer userId){
//        createPdfWithImg();
        try{
            //模板文件
            File file = ResourceUtils.getFile("classpath:ll7.pdf");
            System.out.println(file.getAbsolutePath());
//            String sourceFile = "C:\\Users\\Administrator\\Desktop\\ll7.pdf";
            String sourceFile = file.getAbsolutePath();

            //下载后pdf名
            String fileName = "pdf-test";

            response.setHeader("content-disposition", "attachment;filename=" + fileName + ".pdf");
            response.setContentType("application/octet-stream");
            response.setHeader("Access-Control-Allow-Origin","*");
            OutputStream out = response.getOutputStream();
            //输出到本地
//            FileOutputStream out = new FileOutputStream("D:\\test.pdf");
            //读取模板
            PdfReader  reader = new PdfReader(sourceFile);
            PdfStamper pdfStamper = new PdfStamper(reader, out);
            //设置字体格式
            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            ArrayList<BaseFont> fontList = new ArrayList<>();
            fontList.add(baseFont);
            //获取模板文件中的表单域
            AcroFields afs = pdfStamper.getAcroFields();
            afs.setSubstitutionFonts(fontList);
            //填充文本data


            //Map data = mockData().get("data");

            ResumeVO resume = resumeService.getByUserId(userId);
            if (resume == null) {
                throw new NotFoundException(20010);
            }

            Map<String,Map> map = fillData(resume);

            Map data = map.get("data");

            for (Map.Entry<String, AcroFields.Item> entry : afs.getFields().entrySet()) {
                if (!CollectionUtils.isEmpty(data) && data.get(entry.getKey()) != null) {
                    //Field , 这个是自己在pdf上定义的变量名称
                    afs.setField(entry.getKey(), data.get(entry.getKey()).toString(), true);
                }
            }
            // 处理图片
//            Map imageMap = mockData().get("image");
            Map imageMap = map.get("image");
            for (Map.Entry<String, AcroFields.Item> entry : afs.getFields().entrySet()) {
                if (!CollectionUtils.isEmpty(imageMap) && imageMap.get(entry.getKey()) != null) {
                    String key = entry.getKey();
                    String value = imageMap.get(entry.getKey()).toString();
                    int pageNo = afs.getFieldPositions(key).get(0).page;
                    Rectangle signRect = afs.getFieldPositions(key).get(0).position;
                    float x = signRect.getLeft();
                    float y = signRect.getBottom();
                    //根据路径读取图片
                   Image image = Image.getInstance(value);
                   // Image image = Image.getInstance("C:\\Users\\Public\\Pictures\\10300933262330000.jpg");
                    //获取图片页面
                    PdfContentByte under = pdfStamper.getOverContent(pageNo);
//                    //图片大小自适应
                    image.scaleToFit(signRect.getWidth(), signRect.getHeight());
                    //添加图片
                    image.setAbsolutePosition(x, y);

                    under.addImage(image);

                }
            }
            pdfStamper.setFormFlattening(true);
            pdfStamper.close();
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }


}

